package main

import (
	"log"

	"github.com/micro/go-micro"
	"git.oschina.net/fanbuchi/xgggh/sms/handler"
	"git.oschina.net/fanbuchi/xgggh/sms/subscriber"
	sms "git.oschina.net/fanbuchi/xgggh/sms/proto/sms"
	"fmt"
	"github.com/micro/go-plugins/wrapper/breaker/hystrix"

	"git.oschina.net/fanbuchi/xgggh/sms/db"
)

func main() {


	// New Service
	//http://gogap.cn/2016/05/15/resiliency/
	//https://github.com/micro/go-plugins/tree/master/wrapper
	//在处理崩溃、限制并发、认证、日志、记录

	//这是go-platform和platform https://github.com/micro/go-platform
	//micro解决了基础的组件，Platform则更进一步，解决运行可扩展的服务的更多问题。比如认证、分布式trace、同步锁、健康检查

	service := micro.NewService(
		micro.Name("com.xgggh.srv.sms"),
		micro.Version("latest"),
		micro.BeforeStart(func() error{
			fmt.Println("loading data")
			return nil
		}),
		micro.AfterStop(func () error{
			fmt.Println("close data")
			db.Master().Close()
			return nil
		}),

		micro.WrapClient(hystrix.NewClientWrapper()),
		//micro.WrapHandler(ratelimit.NewHandlerWrapper(&ratelimit.Bucket{},true))
	)

	// Register Handler
	sms.RegisterSmsHandler(service.Server(), new(handler.Sms))

	// Register Struct as Subscriber
	service.Server().Subscribe(
		service.Server().NewSubscriber("topic.com.xgggh.srv.sms", new(subscriber.Sms)),
	)

	// Register Function as Subscriber
	service.Server().Subscribe(
		service.Server().NewSubscriber("topic.com.xgggh.srv.sms", subscriber.Handler),
	)

	// Initialise service
	service.Init()

	// Run service
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}
}
